"""API Client for fetching hydrology forecast data."""

import json
import aiohttp
from typing import Optional, Dict, Any
from pathlib import Path


class ForecastAPIClient:
    """Client for hydrology forecast API."""
    
    def __init__(self, base_url: str = "https://ws.waterism.tech:8090"):
        self.base_url = base_url
        self.cache_dir = Path(__file__).parent.parent.parent / "data" / "cache"
        self.cache_dir.mkdir(parents=True, exist_ok=True)
    
    async def fetch_forecast_data(self, session_id: str, use_cache: bool = True) -> Dict[str, Any]:
        """
        Fetch forecast data from API or cache.
        
        Args:
            session_id: Session ID for the forecast
            use_cache: Whether to use cached data
            
        Returns:
            Dict containing forecast data
        """
        cache_file = self.cache_dir / f"{session_id}.json"
        
        # Try cache first
        if use_cache and cache_file.exists():
            with open(cache_file, 'r', encoding='utf-8') as f:
                return json.load(f)
        
        # Fetch from API
        url = f"{self.base_url}/api/get_hypothetical_info"
        params = {"session_id": session_id}
        
        async with aiohttp.ClientSession() as session:
            async with session.get(url, params=params, ssl=False) as response:
                if response.status != 200:
                    raise Exception(f"API request failed: {response.status}")
                
                data = await response.json()
                
                if not data.get("success"):
                    raise Exception(f"API error: {data.get('message', 'Unknown error')}")
                
                # Cache the result
                with open(cache_file, 'w', encoding='utf-8') as f:
                    json.dump(data, f, ensure_ascii=False, indent=2)
                
                return data
    
    def load_local_data(self, filepath: str) -> Dict[str, Any]:
        """
        Load forecast data from local file.
        
        Args:
            filepath: Path to JSON file
            
        Returns:
            Dict containing forecast data
        """
        with open(filepath, 'r', encoding='utf-8') as f:
            return json.load(f)

